package com.gh.reggie.controller;


import com.gh.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载
 *
 */

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("upload")
    public R<String> upload(MultipartFile file){
        //图片零时地址：C:\Users\Administrator\AppData\Local\Temp\tomcat
        log.info(file.toString());


        //文件名截取方法见sgg文件中的substringtest方法
        //获取文件名(如test.jsp则获取的就是这个全称)
        String originalFilename = file.getOriginalFilename();
        //获取后缀（上面注释的.jsp后缀获取）
        String suffix =  originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件，防止文件重名覆盖原文件
        String fileName = UUID.randomUUID().toString()+suffix;

        //处理存目录文件夹不存在情况：
        File dir = new File(basePath.toString());
        //判断是否存在，不存在创建目录
        if(!dir.exists()){
            System.out.println(dir);
            System.out.println("文件夹不存在");
            dir.mkdirs();
        }else{
            System.out.println("目录存在");
        }

        //新文件构成方式，path在yum中初始化调用，文件名UUID随机生成，后缀截取拼接
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }


    /**
     * 下载文件
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){




        try {
            //输入流，通过输入流读取文件,name前端uploada请求携带的参数
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            //输出流，通过输出流写回浏览器，在浏览器中显示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
